import { Application } from "mydog";
import { cmd } from "../../config/cmd";
import { I_matchRole } from "../svr_match/matchMgr";
import { changeConGameState, changeInfoGameState, getInfoId } from "../util/gameUtil";
import { e_sort_out_type } from "../util/someInterface";
import { DicObj, randInt, removeFromArr } from "../util/util";
import { cardUtil, e_card_arr_type, e_card_color, e_card_score, e_role_type, I_card, I_cardRes } from "./cardLogic";
import { svr_game } from "./svr_game";

export const enum e_roomState {
    
    depositCards, //存底牌阶段
    dealCards,    //发牌  发牌的时候是可以抢做地主的
    drawCard,     //抽牌，抽一张牌作为主的花色
    decideDizhu,  // 确定主家阶段，各家轮流叫分，最低者是主家
    sortOutCards,    //主家整理牌阶段
    normal,       // 正常出牌阶段
}

let dizhuScoreArr: number[] = [0, 1, 2, 3];    // 抢地主时给出的分数

export class Room {
    private app: Application;
    private roomId: number;
    private state!: e_roomState;    // 房间状态
    private nowChairId: number = 0;    // 当前出牌座位号
    private nowTime: number = 0;   // 当前倒计时
    private lastPlayChairId: number = 0; // 上个打出牌的玩家
    private lastWinnerChairId: number = 0; // 上轮胜者



    private lastPlayCardRes: I_cardRes = null as any;    // 上个打出牌的牌组信息
    private firstPlayCardRes: I_cardRes = null as any;    // 当前轮最新出牌的的牌组信息（上轮胜者出的牌）

    private currentPlayChairId: number = 0;               //当前轮出牌的人
    private currentPlayCardResList: { "chairId": number, "cardRes": I_cardRes }[] = [];    // 当前轮玩家出的牌
    
    private players: Player[] = [];
    private uidsid: { "uid": number, "sid": string }[] = [];
    private dipai: I_card[] = [];   //  底牌
    private dizhuChairId: number = 0;   // 地主座位号
    private dizhuMaxScore = 0;  //  抢地主时，出的最高分
    private breakPoint: {point: number, set: number} = {point: 0, set: 0};
    private striveMasterActions: {uid: number, point: number}[] = []; //争取做主家动作列表

    private masterColor!: e_card_color; //当前局的花色
    private rounds: number = 0;   //第几轮出牌

    private cardInRoom!: I_card[]
    private winnerRole!: e_role_type;

    constructor(app: Application, roomId: number) {
        this.app = app;
        this.roomId = roomId;
    }

    setApp(app: Application) {
        this.app = app
    }

    init(roles: I_matchRole[]) {
        let cardArr = cardUtil.genCards(1, true);
        let chairId = 0;
        let gameState = { "gameSvr": this.app.serverId, "roomId": this.roomId };
        for (let one of roles) {
            let p = new Player(one);
            p.chairId = chairId++;
            // p.cards = cardArr.splice(0, 24);
            // p.cards.sort((a, b) => {
            //     return cardUtil.show_compare(a, b, this.masterColor);
            // });

            this.players.push(p);
            this.uidsid.push({ "uid": one.uid, "sid": one.sid });

            changeInfoGameState(one.uid, gameState);
            changeConGameState(one.uid, one.sid, gameState);
        }
        this.cardInRoom = cardArr
        this.dipai = cardArr.splice(0, 12);
        
        // this.masterColor = e_card_color.red;

        let initPoint = cardUtil.getInitBreakPoint(roles.length)
        this.breakPoint = {point: initPoint, set: 0}

        this.state = e_roomState.dealCards;
        this.nowChairId = 0;
        this.nowTime = 2 * 1000;

        this.getMsg(cmd.onGameStart, this.getGameData());
    }

    private getCards() {
        let arr: I_card[] = [];
        let id = 0;
        function push(color: e_card_color) {
            for (let i = 3; i <= 14; i++) {
                arr.push({ "id": id++, "color": color, "score": i });
            }
            arr.push({ "id": id++, "color": color, "score": e_card_score.c2 });
        }
        push(e_card_color.red);
        push(e_card_color.black);
        push(e_card_color.rect);
        push(e_card_color.flower);
        arr.push({ "id": id++, "color": e_card_color.red, "score": e_card_score.kings });
        arr.push({ "id": id++, "color": e_card_color.red, "score": e_card_score.kingb });

        // 打乱
        for (let i = 0; i < arr.length; i++) {
            let index = randInt(arr.length);
            let tmp = arr[index];
            arr[index] = arr[i];
            arr[i] = tmp;
        }
        return arr;
    }


    getGameData() {
        let players: any[] = [];
        for (let one of this.players) {
            players.push(one.toClientJson());
        }
        let info = {
            "state": this.state,
            "nowChairId": this.nowChairId,
            "nowTime": this.nowTime,
            "dipai": this.dipai,
            "dizhuChairId": this.dizhuChairId,
            "dizhuMaxScore": this.dizhuMaxScore,
            "lastPlayChairId": this.lastPlayChairId,
            "players": players,
            "masterColor": this.masterColor,
        }
        return info;
    }

    update(dt: number) {

        if (this.state === e_roomState.depositCards) {
            // 计算第一个要发牌给谁？ 上局是庄家赢得话，就是庄家。是闲家赢得话，就是上局先给发牌的chairid的下一个玩家。
            this.state = e_roomState.dealCards;

            
        }


        if (this.state === e_roomState.dealCards) {
            // TOD should get card from
            if (this.cardInRoom.length === 0) {
                this.nowTime = 20 * 1000;
                this.state = e_roomState.decideDizhu;
                return;
            }
            
            this.nowTime -= dt;
            if (this.nowTime <= 0) {
                this.nowTime = 200;
                let p = this.players[this.nowChairId];
                let dealCards = this.cardInRoom.splice(0, 1);
                p.cards = p.cards.concat(dealCards);
                
                this.getMsg(cmd.onDealCard, { "cards": dealCards, "isOver": false, "nowChairId":  p.chairId});

                if (this.cardInRoom.length === 0) {
                    this.nowTime = 1 * 1000;
                    this.nowChairId = p.chairId
                    this.state = e_roomState.decideDizhu;
                    return;
                }

                this.nowChairId = this.getNextChairId(p.chairId)
                // if (this.nowChairId === this.lastPlayChairId) {
                //     this.getMsg(p.info.uid, [p.cards[p.cards.length - 1].id], () => { });
                // } else {
                //     this.playCard(p.info.uid, [], () => { });
                // }
            }

            
            return;
        }

        if (this.state === e_roomState.decideDizhu) {
            this.nowTime -= dt;
            if (this.nowTime <= 0) {
                // this.state = e_roomState.normal;
                let p = this.players[this.nowChairId];
                this.qiangDizhu(p.info.uid, 0);
                this.nowTime = 20 * 1000;
            }
            return;
        }


        if (this.state === e_roomState.normal) {
            this.nowTime -= dt;
            if (this.nowTime <= 0) {
                let p = this.players[this.nowChairId];
                if (this.nowChairId === this.lastPlayChairId) {
                    this.playCard(p.info.uid, [p.cards[p.cards.length - 1].id], () => { });
                } else {
                    this.playCard(p.info.uid, [], () => { });
                }
            }
            return;
        }

        this.nowTime -= dt;
        if (this.nowTime <= 0) {
            let p = this.players[this.nowChairId];
            this.qiangDizhu(p.info.uid, 0);
        }
    }

    private getMsg(route: number, msg: any = null) {
        this.app.sendMsgByUidSid(route, msg, this.uidsid);
    }

    getNowChairId() {
        return this.nowChairId;
    }
    getNowUid() {
        return this.players[this.nowChairId].info.uid;
    }

    getPlayer(uid: number) {
        let p: Player = null as any;
        for (let one of this.players) {
            if (one.info.uid === uid) {
                p = one;
                break;
            }
        }
        return p;
    }

    private getNextChairId(chairId: number) {
        if (chairId === (this.players.length - 1)) {
            return 0;
        } else {
            return chairId + 1;
        }
    }

    
    setState(state: e_roomState) {
        this.state = state
    }

    // 抢地主
    /**
     * 
     * @param uid 
     * @param score -1代表放弃
     * @returns 
     */
    qiangDizhu(uid: number, score: number) {
        if (this.state !== e_roomState.decideDizhu) {
            console.log(`qiangDizhu uid ${uid} state is not ${e_roomState.decideDizhu}`)
            return;
        }
        console.log(`qiangDizhu ${uid}`)
        let p = this.getPlayer(uid);
        if (p.chairId !== this.nowChairId) {
            console.log('p.chairId !== this.nowChairId')
            return;
        }

        let actions = this.striveMasterActions

        let set = this.breakPoint.set
        console.log(`set = ${set}`)
        //放弃
        if (score == 0) {
            set = set + 1
            this.breakPoint.set = set
            this.nowChairId = this.getNextChairId(p.chairId)
            this.striveMasterActions.push({uid: p.info.uid, point: score})
            
            if (set >= this.players.length) {
                this.dizhuOk(this.dizhuChairId);

                this.masterColor = e_card_color.rect
                this.getMsg(cmd.onSetMasterColor, { "color": this.masterColor, "chairId": p.chairId });
                this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });
            } else {
                this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": -1 });
            }
            return;
        }
        
        if (set >= this.players.length) {
            console.log(`分数小拉`)
            return;
        }

        if (score < cardUtil.getMinBreakPoint(this.players.length)) {
            console.log(`分数小拉2`)
            set = set + 1
            this.breakPoint.set = set
            this.nowChairId = this.getNextChairId(p.chairId);
            this.nowTime = 20 * 1000;
            this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": -1 });
            return;
        }
        console.log(`score = ${score}`)
        console.log(`actions = ${JSON.stringify(actions)}`)
        console.log(`this.breakPoint.point = ${this.breakPoint.point}`)
        // 找到有人抢主
        if (actions.find(a => a.point > -1)) {
            if (score >= this.breakPoint.point) {
                console.log(`qiangDizhu illegle point1`)
                return;
            }
        } else {
            if (score > this.breakPoint.point) {
                console.log(`qiangDizhu illegle point2`)
                return;
            }
        }

       
        set = set + 1
        this.breakPoint = {point: score, set: set}
        this.nowChairId = this.getNextChairId(p.chairId);
        this.striveMasterActions.push({uid: p.info.uid, point: score})
        this.dizhuChairId = p.chairId
        this.nowTime = 20 * 1000;
        this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });

        // todo 
        this.masterColor = e_card_color.rect
        this.getMsg(cmd.onSetMasterColor, { "color": this.masterColor, "chairId": p.chairId });

        if (set >= this.players.length) {
            this.dizhuOk(this.dizhuChairId);
            this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });
        }
        // if (score === 3) {
        //     this.dizhuOk(p.chairId);
        //     this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });
        //     return;
        // }
        // let nextChairId = this.getNextChairId(p.chairId);
        // let nextP = this.players[nextChairId];
        // if (nextP.dizhuScore === -1) {
        //     this.nowChairId = nextChairId;
        //     this.nowTime = 20 * 1000;
        //     this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": -1 });
        //     return;
        // }
        // if (this.dizhuMaxScore === 0) {
        //     this.dizhuOk(0);
        //     this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });
        //     return;
        // }
        // for (let one of this.players) {
        //     if (one.dizhuScore === this.dizhuMaxScore) {
        //         this.dizhuOk(one.chairId);
        //         this.getMsg(cmd.onQiangDizhu, { "score": score, "dizhuChairId": this.dizhuChairId });
        //         break;
        //     }
        // }
    }

    deal(uid: number): void {
        let p = this.getPlayer(uid)

        if (!p) {
            console.log("not find player")
        }

        let card = this.cardInRoom.pop()
        if (!card) {
            console.log("not find card")
            return;
        }
        if (card)
            p.cards.push(card)
    }
    // 抢地主
    // setMasterColor(uid: number, cardId: number) {
    setMasterColor(uid: number, color: e_card_color) {
        console.log(`setMasterColor: ${this.state}`)
        if (this.state !== e_roomState.dealCards) {
            return;
        }
        console.log(`masterColor: ${this.masterColor}`)
        //已设置
        if (this.masterColor) {
            return;
        }
        console.log(`setMasterColor: ${uid}`)
        // console.log("setMasterColor 1")
        let p = this.getPlayer(uid);
        console.log(`cards: ${JSON.stringify(p.cards)}`)
        let card!: I_card;
        // 找出牌组
        for (let one of p.cards) {
            if (one.score === e_card_score.c7  && one.color === color) {
                card = one
                console.log(`card: ${card}`)
                break;
            }
        }
        console.log(`card: ${card}`)
        if (!card) return;
        // if (card.score != e_card_score.c7) return;

        this.masterColor = card.color;
        this.nowChairId = p.chairId;
        this.dizhuChairId = p.chairId;
        this.getMsg(cmd.onSetMasterColor, { "color": this.masterColor, "chairId": p.chairId });
        console.log(`chairId: ${p.chairId} masterColor: ${this.masterColor}`)
        return;
    }

    /**
     * 
     * @param uid 
     * @param id 牌Id
     * @returns 
     */
    addCardToUser(uid: number, id: number) {
       console.log(uid, id)
    }

    // 整理牌组
    sortOutCards(uid: number, cardIds: number[], action: e_sort_out_type) {
        if (uid != this.dizhuChairId) {
            console.log(`sortOutCards: no dizhu`)
            return
        }
        if (this.state !== e_roomState.sortOutCards) {
            console.log(`sortOutCards: state is ${this.state }`)
            return;
        }

        let player = this.getPlayer(this.dizhuChairId)
        let cards = cardUtil.findCards(player.cards, cardIds)

        if (action === e_sort_out_type.in) {
            // TOD should 底牌放到 手牌
            player.cards = [...cards]
            cards.forEach(c => {
                removeFromArr(this.dipai, c)
            })
        } if (action === e_sort_out_type.out) {
            // 牌放到底牌
            this.dipai = [...cards]
            cards.forEach(c => {
                removeFromArr(player.cards, c)
            })
        }

    }

    private dizhuOk(chairId: number) {
        this.state = e_roomState.normal;
        this.dizhuChairId = chairId;
        this.nowChairId = chairId;
        this.nowTime = 20 * 1000;
        this.lastPlayChairId = chairId;
        let p = this.players[chairId];
        // p.cards.push(...this.dipai);
        p.cards.sort((a, b) => {
            return cardUtil.show_compare(a, b, this.masterColor);
        });

        console.log(`dizhu is ${this.dizhuChairId}`)
    }

    // 出牌
    playCard(uid: number, cardIds: number[], next: Function) {
        if (this.state !== e_roomState.normal) {
            console.log('this.state !== e_roomState.normal')
            return;
        }
        let p = this.getPlayer(uid);
        if (p.chairId !== this.nowChairId) {    // 未轮到出牌
            console.log('p.chairId !== this.nowChairId')
            return;
        }
        cardIds = Array.from(new Set(cardIds));     // id去重

        if (cardIds.length === 0) { // 不要
            if (p.chairId === this.lastPlayChairId) {   // 直接出牌时，不能过
                return;
            }
            p.lastPlayCard = [];
            this.nowChairId = this.getNextChairId(p.chairId);
            this.nowTime = 20 * 1000;
            let cardRes: I_cardRes = { "card_arr_type": e_card_arr_type.none, "cards": [], "score": 0 };
            // this.getMsg(cmd.onPlayCard, { "cardRes": cardRes, "isOver": false });
            this.getMsg(cmd.onPlayCard, { "cardRes": cardRes, "isOver": false, "nowChairId":  this.nowChairId});
            return;
        }

        // 找出牌组
        // console.log(JSON.stringify(cardIds))
        // console.log(JSON.stringify(p.cards))
        let cardArr: I_card[] = [];
        for (let id of cardIds) {
            let find = false;
            for (let one of p.cards) {
                if (one.id === id) {
                    cardArr.push(one);
                    find = true;
                    break;
                }
            }
            if (!find) {
                console.log("! find")
                return;
            }
        }
        cardArr.sort((a, b) => {
            return cardUtil.show_compare(a, b, this.masterColor);
        });
        // console.log('this.lastPlayChairId:' + this.lastPlayChairId)
        // console.log('p.chairId:' + p.chairId)
        if (this.nowChairId === p.chairId) { // 直接出牌

            
            let cardRes : I_cardRes = { "card_arr_type": e_card_arr_type.none, "cards": cardArr, "score": e_card_score.c3 };
            if (this.currentPlayCardResList.length == 0) {
                this.playCardOk(p, cardRes);
                return;
            }
            
            // if (cardRes.card_arr_type === e_card_arr_type.none) {
            let res = cardUtil.can_be_select(
                this.currentPlayCardResList[0].cardRes.cards,
                this.masterColor, 
                p.cards, 
                [], 
                cardArr[0]);
            if (!res) {
                next({ "code": 1, "info": "非法牌组" })
                return;
            }
            this.playCardOk(p, cardRes);
            return;
        }

        // 必须比上家大
        /*
        let res = this.isBigger(cardArr);
        if (!res.bigger) {
            next({ "code": 2, "info": "非法牌组或要不起" })
            return;
        }
        */

        //下家，需要检验是否非法牌组
        let res = this.isLegal(cardArr, p.cards);
        if (!res.legal) {
            next({ "code": 2, "info": "非法牌组" })
            return;
        }

        this.playCardOk(p, res.cardRes);
    }

    autoPlay() {
        let player = this.players[this.nowChairId]
        let card!: I_card;
        let cards!: I_card[];

        if (!player.cards.length) return;

        cards = []

        if (this.currentPlayCardResList.length == 0) {
            card = player.cards[0]

            let cardsArr: I_card[][] = cardUtil.cards_can_be_play(player.cards)
            cards = cardsArr[0]

        } else {
            let firstCard = this.currentPlayCardResList[0].cardRes.cards
            // console.log('firstCard = ' + JSON.stringify(firstCard))
            let playerCards = [...player.cards]
            // console.log('playerCards = ' + JSON.stringify(playerCards))
            
            for (let i=0; i<firstCard.length; i++) {
                let select_card = cardUtil.select_card(
                    playerCards,
                    this.masterColor,
                    this.currentPlayCardResList[0].cardRes.cards
                )

                removeFromArr(playerCards, select_card)
                cards.push(select_card)
            }
        }
        
        // console.log(`player ${this.players[this.nowChairId].info.uid}:${JSON.stringify(cards)}`)

        let cardInPlayerCards = true
        for (let i=0; i<cards.length; i++) {
            cardInPlayerCards = false
            for (let j=0; j<player.cards.length; j++) {
                if (cards[i].id == player.cards[j].id) {
                    // console.log(`${cards[i].id} == ${player.cards[j].id}`)
                    cardInPlayerCards = true
                }
            }
        }

        if (!cardInPlayerCards)
            console.log(`cardInPlayerCards`)

        this.playCard(player.info.uid, cards.map(c => { return c.id}), () => {})

        
    }

    private playCardOk(p: Player, cardRes: I_cardRes) { //出牌合法
        this.lastPlayChairId = p.chairId;
        this.lastPlayCardRes = cardRes;
        this.nowChairId = this.getNextChairId(p.chairId);
        this.nowTime = 20 * 1000;

        // 新的一轮
        if (!this.currentPlayCardResList) {
            this.firstPlayCardRes = cardRes
        }

        this.currentPlayCardResList.push({"chairId": p.chairId, "cardRes": cardRes});

        for (let one of cardRes.cards) {
            removeFromArr(p.cards, one);
        }
        p.lastPlayCard = cardRes.cards;
        let isOver = false;
        // if (p.cards.length === 0) { //游戏结束
        //     isOver = true;
        // }
        
        let roundOver = false
        let numberInRound = this.currentPlayCardResList.length
        //当前轮大家都出完牌
        if (this.currentPlayCardResList.length == this.players.length) {
            //下一轮由胜者出牌
            // cardres = currentPlayCardResList;
            // console.log(JSON.stringify(this.currentPlayCardResList, null, '  '))
            let winnerIndex = this.getWinnerInRound(this.currentPlayCardResList)
            let point = this.getPointsInRound(this.currentPlayCardResList)
            let player = this.players[winnerIndex];
            player.addPoint(point)

            console.log('winner is:' + this.players[player.chairId].info.uid)
            for(let i = 0; i < this.players.length; i++) {
                console.log(`id ${this.players[i].info.uid}: ${this.players[i].points}`);
            }

            this.nowChairId = winnerIndex;

            //设置胜者 下轮由他先出牌 todo
            this.lastWinnerChairId = 0;
            //计算得分
            //calculate points
            //清理
            this.currentPlayCardResList = [];
            roundOver = true
        }
        this.getMsg(cmd.onPlayCard, { "cardRes": cardRes, "isOver": isOver, "nowChairId":  this.nowChairId, "roundOver": roundOver, "numberInRound": numberInRound});
        // 全部牌都打完拉
        isOver = !this.players.some(player => {
            return player.cards.length > 0
        })
        // console.log(`isOver = ${isOver}`)
        if (isOver) {
            // this.jiesuan(p.chairId);
            let role = this.calcWinnerRole()
            console.log(`winner role is ${role}`)
        }


    }

    /**
     * 胜利的角色是谁
     * @returns 
     */
    private calcWinnerRole(): e_role_type {
        let masterPoint = this.players[this.dizhuChairId].points

        for(let i = 0; i < this.players.length; i++) {
            console.log(`id ${this.players[i].info.uid}: ${this.players[i].points}`);
        }

        console.log(`this.dizhuChairId is ${this.dizhuChairId}`)
        console.log(`masterPoint is ${masterPoint}`)
        console.log(`breakPoint is ${this.breakPoint.point}`)
        return masterPoint >= this.breakPoint.point ? e_role_type.master: e_role_type.ordinary
    }

    private jiesuan(winChairId: number) {
        let list: { "chairId": number, "gold": number }[] = [];
        let dizhuP = this.players[this.dizhuChairId];
        if (winChairId === this.dizhuChairId) {   // 地主胜
            let gold = 0;
            for (let one of this.players) {
                if (one !== dizhuP) {
                    let tmpGold = 0;
                    if (one.info.gold >= 10) {
                        tmpGold = 10;
                    } else {
                        tmpGold = one.info.gold;
                    }
                    gold += tmpGold;
                    // this.app.rpc(getInfoId(one.info.uid)).info.main.gameOver({ "uid": one.info.uid, "isWin": false, "addGold": -tmpGold });
                    list.push({ "chairId": one.chairId, "gold": -tmpGold });
                }
            }
            // this.app.rpc(getInfoId(dizhuP.info.uid)).info.main.gameOver({ "uid": dizhuP.info.uid, "isWin": true, "addGold": gold });
            list.push({ "chairId": dizhuP.chairId, "gold": gold });

        } else {    // 农民胜
            let gold = 0;
            if (dizhuP.info.gold >= 20) {
                gold = 20;
            } else {
                gold = dizhuP.info.gold;
            }
            let halfGold = Math.floor(gold / 2);
            for (let one of this.players) {
                if (one !== dizhuP) {
                    // this.app.rpc(getInfoId(one.info.uid)).info.main.gameOver({ "uid": one.info.uid, "isWin": true, "addGold": halfGold });
                    list.push({ "chairId": one.chairId, "gold": halfGold });
                }
            }
            // this.app.rpc(getInfoId(dizhuP.info.uid)).info.main.gameOver({ "uid": dizhuP.info.uid, "isWin": false, "addGold": -gold });
            list.push({ "chairId": dizhuP.chairId, "gold": -gold });
        }

        this.getMsg(cmd.onGameOver, { "winChairId": winChairId, "list": list });
        // svr_game.roomMgr.delRoom(this.roomId);
    }

    private isBigger(cardArr: I_card[]): { "bigger": boolean, "cardRes": I_cardRes } {
        if (cardUtil.isWangZha(cardArr)) {
            return { "bigger": true, "cardRes": { "card_arr_type": e_card_arr_type.wang_zha, "score": e_card_score.kings, "cards": cardArr } };
        }
        let last = this.lastPlayCardRes;
        if (cardUtil.isZha(cardArr)) {
            if (last.card_arr_type === e_card_arr_type.wang_zha) {
                return { "bigger": false, "cardRes": null as any };
            } else if (last.card_arr_type === e_card_arr_type.zha) {
                if (cardArr[0].score > last.score) {
                    return { "bigger": true, "cardRes": { "card_arr_type": e_card_arr_type.zha, "score": cardArr[0].score, "cards": cardArr } };
                } else {
                    return { "bigger": false, "cardRes": null as any };
                }
            } else {
                return { "bigger": true, "cardRes": { "card_arr_type": e_card_arr_type.zha, "score": cardArr[0].score, "cards": cardArr } };
            }
        }

        if (last.card_arr_type === e_card_arr_type.wang_zha || last.card_arr_type === e_card_arr_type.zha) {
            return { "bigger": false, "cardRes": null as any };
        } else if (last.cards.length !== cardArr.length) {
            return { "bigger": false, "cardRes": null as any };
        } else {
            let cardRes = cardUtil.isCardType(cardArr, last.card_arr_type);
            if (cardRes.card_arr_type === e_card_arr_type.none) {
                return { "bigger": false, "cardRes": null as any };
            } else if (cardRes.score > last.score) {
                return { "bigger": true, "cardRes": cardRes };
            } else {
                return { "bigger": false, "cardRes": null as any };
            }
        }
    }

    /**
     * 判断打出的牌是否合法
     * @param cardFirst  最先出牌
     * @param card       当前想出的牌
     * @param cardInHand 手中的牌
     * @returns 
     */
     private isLegalOne(cardFirst: I_card[], card: I_card, cardInHand: I_card[]): { "legal": boolean, "cardRes": I_cardRes } {
        

        /**
         * 一张、一张比对
         * 
         * 1找出先出牌人的牌的花色 currentRoundColor
         * 2比对下自己有没有     currentRoundColor
         * 3满足的话必须出       currentRoundColor 一样花色的牌
         * 4不满足 随便出
         * 
         */
         return { "legal": false, "cardRes": null as any };
    }
    

    /**
     * 判断打出的牌是否合法
     * @param cardArr 
     * @returns 
     */
    private isLegal(cardArr: I_card[], cardInHand: I_card[]): { "legal": boolean, "cardRes": I_cardRes } {
        if (cardUtil.isWangZha(cardArr)) {
            return { "legal": true, "cardRes": { "card_arr_type": e_card_arr_type.wang_zha, "score": e_card_score.kings, "cards": cardArr } };
        }
        let last = this.lastPlayCardRes;
        let firstCards = this.firstPlayCardRes

        /**
         * 一张、一张比对
         * 
         * 1找出先出牌人的牌的花色 currentRoundColor
         * 2比对下自己有没有     currentRoundColor
         * 3满足的话必须出       currentRoundColor 一样花色的牌
         * 4不满足 随便出
         * 
         */

        if (cardUtil.isZha(cardArr)) {
            if (last.card_arr_type === e_card_arr_type.wang_zha) {
                return { "legal": false, "cardRes": null as any };
            } else if (last.card_arr_type === e_card_arr_type.zha) {
                if (cardArr[0].score > last.score) {
                    return { "legal": true, "cardRes": { "card_arr_type": e_card_arr_type.zha, "score": cardArr[0].score, "cards": cardArr } };
                } else {
                    return { "legal": false, "cardRes": null as any };
                }
            } else {
                return { "legal": true, "cardRes": { "card_arr_type": e_card_arr_type.zha, "score": cardArr[0].score, "cards": cardArr } };
            }
        }

        if (last.card_arr_type === e_card_arr_type.wang_zha || last.card_arr_type === e_card_arr_type.zha) {
            return { "legal": false, "cardRes": null as any };
        } else if (last.cards.length !== cardArr.length) {
            return { "legal": false, "cardRes": null as any };
        } else {
            let cardRes = cardUtil.isCardType(cardArr, last.card_arr_type);
            if (cardRes.card_arr_type === e_card_arr_type.none) {
                return { "legal": false, "cardRes": null as any };
            } else if (cardRes.score > last.score) {
                return { "legal": true, "cardRes": cardRes };
            } else {
                return { "legal": false, "cardRes": null as any };
            }
        }
    }

    /**
     * 比较谁是胜利者
     */
    private getWinnerInRound(res: { "chairId": number, "cardRes": I_cardRes }[]): number {
        // let cardsInRound = [
        //     [{ "id": 8,"color": e_card_color.rect, "score": e_card_score.c6}, { "id": 8,"color": e_card_color.rect, "score": e_card_score.c6}],
        //     [{ "id": 8,"color": e_card_color.black, "score": e_card_score.c5}, { "id": 8,"color": e_card_color.black, "score": e_card_score.c5}],
        //     [{ "id": 8,"color": e_card_color.rect, "score": e_card_score.c10}, { "id": 8,"color": e_card_color.rect, "score": e_card_score.c10}],
        //     [{ "id": 8,"color": e_card_color.red, "score": e_card_score.c2}, { "id": 8,"color": e_card_color.black, "score": e_card_score.c2}],
        // ]
        let cardsInRound: I_card[][] = []
        res.forEach(r => {
            cardsInRound.push(r.cardRes.cards)
        })
        let index = cardUtil.get_winner(cardsInRound, this.masterColor)
        // console.log(res)
        // console.log('index=' + index);
        // console.log('index=' + res[index].chairId);
        return res[index].chairId;
    }

    private getPointsInRound(res: { "chairId": number, "cardRes": I_cardRes }[]): number {
        let points = 0;
        let cardsInRound: I_card[][] = []
        res.forEach(r => {
            cardsInRound.push(r.cardRes.cards)
        })
        points = cardUtil.get_points(cardsInRound)
        return points;
    }

    getCurrentPlayCardResList() {
        return this.currentPlayCardResList;
    }

    // 离开房间
    leave(uid: number) {
        let p = this.getPlayer(uid);
        p.info.sid = "";
        for (let i = 0; i < this.uidsid.length; i++) {
            if (this.uidsid[i].uid === uid) {
                this.uidsid.splice(i, 1)
                break;
            }
        }
    }

    // 重新进入房间
    enter(info: { "uid": number, "sid": string }) {
        let p = this.getPlayer(info.uid);
        if (!p) {
            return false;
        }
        p.info.sid = info.sid;
        for (let i = 0; i < this.uidsid.length; i++) {
            if (this.uidsid[i].uid === info.uid) {
                this.uidsid.splice(i, 1)
                break;
            }
        }
        this.uidsid.push(info);
        // this.app.sendMsgByUidSid(cmd.onGameStart, this.getGameData(), [info]);
        return true;
    }
}


export class Player {
    info: I_matchRole;
    chairId: number = 0;    // 座位号
    cards: I_card[] = [];   // 手中牌组
    dizhuScore: number = -1;  // 抢地主时给出的的分数  (-1还未抢，0不要，1、2、3分)
    lastPlayCard: I_card[] = [];    // 上一次出的牌
    points: number = 0; //得分
    constructor(info: I_matchRole) {
        this.info = info;
    }

    addPoint(point: number): void {
        this.points += point;
    }

    toClientJson() {
        return {
            "uid": this.info.uid,
            "nickname": this.info.nickname,
            "gold": this.info.gold,
            "chairId": this.chairId,
            "cards": this.cards,
            "lastCards": this.lastPlayCard,
        }
    }
}